<?php

/**
 * This is the model class for table "home".
 */
class Home extends CActiveRecord
{
	public $images;
	public $isParse = false;
	
	// параметры для фильтра 
	public $floor_from, $floor_to;
	public $cost_from, $cost_to;
	public $without_photo, $only_new;
	
	private $_url;
	
	public function tableName() {
		return 'home';
	}

	public function rules() {
		return array(
			array('url', 'unique'),
			array('street, phone', 'required'),
			array('max_floor, furniture, home, type, city_id, floor_from, cost_from, cost_to,
					 floor_to, district_id, metro_id, owner_id, furniture, cooker,
					 wash_machine, fridge, cost, area, without_photo, only_new, title_temp_id', 'numerical', 'integerOnly'=>true),
			array('street, yandex_map, phone, house_type', 'length', 'max'=>64),
			array('url,title', 'length', 'max'=>256),
			array('house', 'length', 'max'=>8),
			array('description, manager_comment, title', 'safe'),
			array('max_floor, yandex_map, house, home,id, type, city_id, floor_from, cost_from,
					 cost_to, floor_to, district_id, description, metro_id, address, owner_id, floor,
					 furniture, cooker, wash_machine, fridge, cost, area,
					 house_type, url, isParse, home, without_photo, only_new, manager_comment, title, title_temp_id', 
					 'safe', 'on'=>'search'),
		);
	}

	public function relations() {
		return array(
			'commentOnHomes' => array(self::HAS_MANY, 'CommentOnHome', 'home_id'),
			'houseType' => array(self::BELONGS_TO, 'HouseType', 'house_type'),
			'city' => array(self::BELONGS_TO, 'City', 'city_id'),
			'district' => array(self::BELONGS_TO, 'Discrict', 'district_id'),
			'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),
			'metro' => array(self::BELONGS_TO, 'Metro', 'metro_id'),
			'homePhotoses' => array(self::HAS_MANY, 'HomePhotos', 'home_id'),
		);
	}

	public function attributeLabels() {
		return array(
			'id' => 'ID',
			'type' => 'Тип квартиры',
			'city_id' => 'Город',
			'district_id' => 'Район',
			'metro_id' => 'Метро',
			'address' => 'Адрес',
			'owner_id' => 'Собственник',
			'floor' => 'Этаж',
			'furniture' => 'Мебель',
			'cooker' => 'Плита',
			'wash_machine' => 'Стиральная машина',
			'fridge' => 'Холодильник',
			'cost' => 'Стоимость',
			'area' => 'Площадь (кв.м)',
			'without_photo' => '+ без фото',
			'only_new' => 'Только новые',
			'street' => 'Адрес','Улица',
			'house' => 'Номер дома',
			'home' => 'Номер квартиры',
			'max_floor' => 'Этажность дома',
			'description' => 'Описание',
			'yandex_map' => 'Параметры для карты',
			'phone' => 'Телефон хозяина',
			'house_type' => 'Тип дома',
			'url' => 'Внешний адрес', 
			'manager_comment' => 'Комментарий нашего менеджера'
		);
	}

	public function scopes()
	{
		return array(
			'published'=>array(
				'condition'=>'t.cost > 0',
			),
		);
	}
	
	public function getUrl() {
		return Yii::app()->createUrl('home/view',array('city'=>$this->city->url_code, 'id'=>$this->id));
	}
	
	public function getUpdateTime() {
		return strtotime($this->date);
	}
	
	public function search (&$pages) {
		$criteria = new CDbCriteria;	
		
		$criteria = new CDbCriteria();
		$count = $this->count($criteria);
		
		//$criteria->compare('id',$this->id);
		if (!empty($this->type)) {
			if (!is_array($this->type))
				$criteria->addCondition('id',$this->id);
			else
				$criteria->addInCondition('type', $this->type);
		}
		if (!empty($this->floor_from)) {
			$criteria->addCondition('floor >= :floor_from');
			$criteria->params[':floor_from'] = $this->floor_from;
		}
		if (!empty($this->floor_to)) {
			$criteria->addCondition('floor <= :floor_to');
			$criteria->params[':floor_to'] = $this->floor_to;
		}
		
		$criteria->compare('city_id',$this->city_id);
		$criteria->compare('district_id', $this->district_id, true);
		$criteria->compare('metro_id',$this->metro_id, true);
		
		if (!empty($this->cost_from)) {
			$criteria->addCondition('cost >= :cost_from');
			$criteria->params[':cost_from'] = $this->cost_from;
		}
		if (!empty($this->cost_to)) {
			$criteria->addCondition('cost <= :cost_to');
			$criteria->params[':cost_to'] = $this->cost_to;
		}
		
		if (!empty($this->furniture))
			$criteria->compare('furniture', $this->furniture);
		if (!empty($this->cooker))
			$criteria->compare('cooker', $this->cooker);
		if (!empty($this->wash_machine))
			$criteria->compare('wash_machine', $this->wash_machine);
		if (!empty($this->fridge))
			$criteria->compare('fridge', $this->fridge);
		
		$criteria->compare('status', 1);
		
		$pages = new CPagination($count);
		
		$pages->pageSize = 10;
		$pages->applyLimit($criteria);
		
		$criteria->order = 'date DESC';
		
		// c фото или без фото
		$oper = '>';
		if (!empty($this->without_photo) && $this->without_photo>0) {
			$oper = '>=';
		} 
		
		$criteria->compare('(SELECT count(*) FROM home_photos WHERE home_id=t.id)', $oper.'0');
		
		if (!empty($this->only_new) && $this->only_new>0) {
			$criteria->addCondition('DATE(NOW()) - INTERVAL 5 DAY <= DATE(t.date)');
		}
		//$criteria->compare('address',$this->address,true);
		//$criteria->compare('owner_id',$this->owner_id);
		//$criteria->compare('floor',$this->floor,true);
		/*$criteria->compare('comment_id',$this->comment_id);
		$criteria->compare('comment_text',$this->comment_text);
		
		$criteria->compare('cost',$this->cost);
		$criteria->compare('area',$this->area);*/
		
		//die(print_r($_GET,1));
		
		return new CActiveDataProvider($this, array(
			
			'pagination' => $pages,
			'criteria' => $criteria,
		));
	}

	public static function model ($className=__CLASS__) {
		return parent::model($className);
	}
	
	public function getTypes () {
		return array(
			'0'=>'K',
			'1'=>'1',
			'2'=>'2',
			'3'=>'3',
			'4'=>'4+',
		);
	}
	
	public function getCities () {
		$models = City::model()->findAll(
			array(
				'condition'=>'id > :id',
    			'params'=>array(':id'=>0),
				'order' => 'caption'
		));
	
		$list = CHtml::listData($models, 'id', 'caption');
	
		return $list;
	}
	
	public function getMetros ($city_id = 0) {
		if ($city_id == 0) {
			if (empty($this->attributes['city_id']))
				return array();
			else 
				$city_id = $this->attributes['city_id'];
		}
		
		$metro = Metro::model()->findAll('city_id=:city_id AND id > :id', array(':city_id' => $city_id, 'id' => 0));
		$metro = CHtml::listData($metro, 'id', 'caption');
		
		return $metro;
	}
	
	public function getDiscricts ($city_id = 0) {
		if ($city_id == 0) {
			if (empty($this->city_id))
				return array();
			else 
				$city_id = $this->city_id;
		}
	
		$district = Discrict::model()->findAll('city_id=:city_id AND id > :id', array(':city_id' => $city_id, 'id' => 0));
		$district = CHtml::listData($district, 'id', 'caption');
	
		return $district;
	}
	
	public function beforeSave () {
		
		$address = $this->getAddress(false);		
		$city = City::model()->findByPk($this->city_id);
		$cityName = $city->caption;
		
		$json = MiscHelper::getContent('http://geocode-maps.yandex.ru/1.x/?'.http_build_query(array(
			'geocode' => $cityName.','.$address,
			'format' => 'json'
		)));
		$yaObject = json_decode($json);
		//echo '<pre>'.print_r($yaObject, 1).'</pre>';
		$coorsStr = $yaObject->response->GeoObjectCollection->featureMember[0]->GeoObject->Point->pos;
		
		$post = array(
			'kind'=>'district',
			'results' => 1,
			'format'=>'json',
			'geocode'=>$coorsStr,
		);
		
		$url = 'http://geocode-maps.yandex.ru/1.x/?'.http_build_query($post);
		$json = MiscHelper::getContent($url);
		
		$yaObject = json_decode($json);
		$district = $yaObject->response->GeoObjectCollection->featureMember[0]->GeoObject->name;
		
		$district = explode(' ', $district);
		$district = $district[0];
		$criteria = new CDbCriteria;
		$criteria->select = 'id';
		$criteria->compare('caption', $district);
		
		$dis = Discrict::model()->find($criteria);
		if (!empty($dis) && $dis->id > 0) {
			$this->district_id = $dis->id;
		}
		
		$coors = explode(' ', $coorsStr);
		
		$this->yandex_map = $coors[1].', '.$coors[0];
		
		if ($this->isParse > 0) {
			$this->owner_id = -1;
		} elseif ($this->isNewRecord) {
			$this->owner_id = 1; // Yii::app()->user->getId();
		}
		
		if (!empty($this->house)) {
			$this->street = str_ireplace(',', '', $this->street);
		}
		
		if($this->isNewRecord) {
			$this->date = new CDbExpression('NOW()');
		}
		
		$criteria = new CDbCriteria;
		$criteria->order = 'rand()';
		
		$templ = HomeTemplate::model()->find($criteria);
		$title = $templ->template;
			
		$caption = $this->getTypeStr($templ->word_form);
		$address = $this->getAddress();
		$address .= ', '.$this->city->caption.', '.$this->cost.' руб.';
			
		$this->title = str_ireplace(
			array('#caption#', '#address#'),
			array($caption, $address),
			$title
		);
			
		$this->title_temp_id = $templ->id;
			
		//echo '<pre>'.print_r($this, 1).'</pre>'; die();
			
		//$home->save();
		
		return parent::beforeSave();
	}
	
	public static function getFilter() {
		// TODO: сделать взятия айдишника либо из урла, либо из сессии
		$city_id = 1;
		
		$city = City::model()->findByPk($city_id);
		$cityCode = $city->url_code;
		
		$model = new Home;
		$model->attributes = Yii::app()->request->getParam('Home', array('city_id'=>$city_id));
		$metro = $model->getMetros($city_id);
		$district = $model->getDiscricts($city_id);
		$types = $model->getTypes();
		
		$filter = array (
			'city_code' => $cityCode,
			'types' => $types,
			'model' => $model,
			'metro' => $metro,
			'districts'=> $district,
		);
		
		return $filter;
	}
	
	public function getPhone() {
		$src = false;
	
		if ($this->owner_id > 0) {
			$src = ImageResizer::getPhoneImgSrc($this->owner->phone);
		} else {
			$src = ImageResizer::getPhoneImgSrc($this->phone);
		}

		return $src;
	}
	
	public function afterSave () {
		if (!$this->isParse) {
			$images = CUploadedFile::getInstances($this, 'images');
			if (isset($images) && count($images) > 0) {
				foreach($images as $k => $img) {
					$imageName = md5(microtime()) . '.jpg';
					$path = Home::getFolder($imageName, true).$imageName;
					if ($img->saveAs($path)) {
						$advImg = new HomePhotos();
						$advImg->home_id = $this->getPrimaryKey();
						$advImg->path = $imageName;
						$advImg->save();
							
						//print_r($advImg->getErrors());
					}
				}
			}
		} // avito.ru
		else {
			if (isset($this->images) && count($this->images) > 0) {
				$images = MiscHelper::getContent($this->images);
				foreach($images as $k => $image) {
					if ($this->isParse == 1) {
						$type = @exif_imagetype('http://'.$k);
						if ($type <= 0) continue;
					}
					$imageName = md5(microtime().$k) . '.jpg';
					$path = Home::getFolder($imageName, true).$imageName;
					
					file_put_contents($path, $image);

					if ($this->isParse == 1)
						ImageResizer::cutImage($path, array('h'=>80));			
					
					$advImg = new HomePhotos();
					$advImg->home_id = $this->getPrimaryKey();
					$advImg->path = $imageName;
					$advImg->save();
			
					//print_r($advImg->getErrors());
				}
			}
		}
	}
	
	public static function getFolder($imageName, $withWebRoot = false) {
		$folder = $withWebRoot ? Yii::getPathOfAlias('webroot') : '';
		$folder .=  '/uploads/catalog/'.substr($imageName, 0, 3).'/';
		
		if (is_dir($folder) == false)
			@mkdir($folder, 0755, true);
		return $folder;
	}
	
	public function getAddress($with_home = true) {
		$str = (stripos($this->street, 'ул') === false ? 'ул. ' : '').
			MiscHelper::firstToUpper($this->street).
			(!empty($this->house) ? ', ' : '').$this->house;
		
		if ($with_home)
			$str .= !empty($this->home) ? ', кв. '.$this->home : "";
		
		return $str;
	}
	
	public function getH1 () {
		$str = '';
		$str= $this->getTypeStr();
		$str .= ', '.$this->getAddress();
		
		return $str;
	}
	
	public function getTypeStr ($word_form = 0, $type = -1) {
		if ($type == -1) {
			$type = $this->type;
		}
		
		$str = '';
		if ($type == 0) {
			$str = 'комнат';
			
			switch ($word_form) {
				case 0: $str .= 'а'; break;
				case 1: $str .= 'ы'; break;
				case 2: $str .= 'у'; break;
			}
			
		} elseif ($type < 4) {
			$str = $this->type.'-комнатн';
			switch ($word_form) {
				case 0: $str .= 'ая'; break;
				case 1: $str .= 'ой'; break;
				case 2: $str .= 'ую'; break;
			}
			
			$str .= ' квартир';
			switch ($word_form) {
				case 0: $str .= 'а'; break;
				case 1: $str .= 'ы'; break;
				case 2: $str .= 'у'; break;
			}
		} else {
			$str = 'квартир';
			switch ($word_form) {
				case 0: $str .= 'а'; break;
				case 1: $str .= 'ы'; break;
				case 2: $str .= 'у'; break;
			}
			
			$str .= ' 4+';
		}
		return $str;
	}
	
	public function getParentSection () {
		$url = '/catalog/'.$this->city->url_code.'/';
		
		$criteria = new CDbCriteria;
		$criteria->compare('type', $this->type);
		$url .= HomeTypeTemplate::model()->find($criteria)->url_part.'/';

		$criteria = new CDbCriteria;
		$criteria->compare('url', $url);
		
		$innerLink = InnerLink::model()->find($criteria);
		//die($url);
		//die(print_r($criteria,1));
		return array(
			'url' => $innerLink->url,
			'caption' => $innerLink->h1
		);
	}
}
